package cn.iluwen.airline.Config;

import org.springframework.stereotype.Component;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 * Cookie工具类
 */
@Component
public class CookieUtil {
    
    /**
     * 创建一个Cookie
     */
    public static void setCookie(HttpServletResponse response, String name, String value, int maxAge) {
        Cookie cookie = new Cookie(name, value);
        cookie.setPath("/");              // 设置为网站根目录
        cookie.setMaxAge(maxAge);         // 过期时间，单位为秒
        cookie.setHttpOnly(true);         // 禁止JS访问
        cookie.setSecure(false);           // 只在HTTPS连接中传输
        
        // 添加SameSite=None属性以支持跨域
        // 由于Cookie类不直接支持SameSite属性，使用response header设置
        String cookieString = String.format("%s=%s; Max-Age=%d; Path=/; HttpOnly; Secure; SameSite=None", 
                                           name, value, maxAge);
        response.setHeader("Set-Cookie", cookieString);
    }
    
    /**
     * 获取Cookie的值
     */
    public static String getCookieValue(HttpServletRequest request, String name) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (name.equals(cookie.getName())) {
                    return cookie.getValue();
                }
            }
        }
        return null;
    }
    
    /**
     * 删除Cookie
     */
    public static void deleteCookie(HttpServletResponse response, String name) {
        Cookie cookie = new Cookie(name, "");
        cookie.setPath("/");
        cookie.setMaxAge(0); // 将过期时间设为0，即立即过期
        cookie.setHttpOnly(true);
        cookie.setSecure(true);  // 只在HTTPS连接中传输
        
        // 使用响应头设置SameSite=None属性
        String cookieString = String.format("%s=; Max-Age=0; Path=/; HttpOnly; Secure; SameSite=None", name);
        response.setHeader("Set-Cookie", cookieString);
    }
} 